package com.zxl.manager.privacy.utils.track.crash;

import android.util.Log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

/**
 * 
 * 异常信息收集
 * 类名称：ExceptionUtils
 * 类描述：
 * 创建人：makai
 * 修改人：makai
 * 修改时间：2014年6月4日 下午6:05:31
 * 修改备注：
 * @version 1.0.0
 *
 */
public class ExceptionUtils {
	
	public static final String STACK_TRACE_KEY = "stack_trace_key";
	
	static final String ERROR_FILE_TYPE = "_stk.txt";
	
	public static String getStackTraceString(Throwable e) {
		Writer result = new StringWriter();
		PrintWriter printWriter = new PrintWriter(result);
		printWriter.append(e.getMessage());
		e.printStackTrace(printWriter);
		Log.getStackTraceString(e);
		Throwable cause = e.getCause();
		while (cause != null) {
			cause.printStackTrace(printWriter);
			cause = cause.getCause();
		}
		return result.toString();
	}
	
	/**
	 * When a report can't be sent, it is saved here in a file in the root of
	 * the application private directory.
	 */
	public static String saveCrashReportFile(String path, Properties mCrashProperties) {
		try {
			long timestamp = System.currentTimeMillis();
			String fileName = createSaveFilePath(path);
			fileName += "stack-" + timestamp + ERROR_FILE_TYPE;
			File file = new File(fileName);
			FileOutputStream trace = new FileOutputStream(file, true);
			String track = mCrashProperties.getProperty(STACK_TRACE_KEY);
			mCrashProperties.setProperty(STACK_TRACE_KEY, track);
			storeToOutputStream(trace, mCrashProperties);
			trace.flush();
			trace.close();
			return fileName;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static synchronized void storeToOutputStream(OutputStream out, Properties properties)
			throws IOException {
		if (properties == null) {
			return;
		}
		String lineSeparator = "#"; //System.getProperty("line.separator");
		StringBuilder buffer = new StringBuilder(200);
		OutputStreamWriter writer = new OutputStreamWriter(out, "ISO8859_1"); //$NON-NLS-1$
		// 输出日期
		writer.write("#"); //$NON-NLS-1$
		writer.write(new Date().toString());
		writer.write(lineSeparator);

		for (Map.Entry<Object, Object> entry : properties.entrySet()) {
			String key = (String) entry.getKey();
			buffer.append(key);
			buffer.append('=');
			buffer.append(entry.getValue());
			buffer.append(lineSeparator);
			writer.write(buffer.toString());
			buffer.setLength(0);
		}
		writer.flush();
	}
	
	private static String createSaveFilePath(String mCrashFilePath) {
		File destDir = new File(mCrashFilePath);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		return mCrashFilePath;
	}
	
}
